package com.cqsw.service.impl;

import com.cqsw.entity.Role;
import com.cqsw.entity.Users;
import com.cqsw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Classname MyUserDetailsService
 * @Description TODO
 * @Date 2022/6/13 19:15
 * @Created by Smith.Liu
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    private final UserMapper userMapper;

    @Autowired
    public MyUserDetailsService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userMapper.selectByUsername(username);
        if (ObjectUtils.isEmpty(users)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roles = userMapper.getRoleForUser(users.getId());
        users.setRoles(roles);
        return users;
    }
}
